package com.chungkui.check.expression.impl;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author jason
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class AviatorExpression extends BaseExpression {
    private final Logger log = LoggerFactory.getLogger(AviatorExpression.class);
    Expression expression;
    private String code;
    @Override
    public CheckResult match(Map<String, Object> params) {
        boolean result = true;
        CheckResult checkResult = new CheckResult(true);
        try {
            if (this.expression != null) {
                result = (Boolean) this.expression.execute(params);
            }
            if (result) {
                return checkResult;
            }
            checkResult.setMsg(MapUtils.getString(this.msg, Constants.FAIL, this.normalMsg));

        } catch (Exception e) {
            log.info("MATCH ERROR", e);
            checkResult.setMsg(MapUtils.getString(this.msg, "error", this.normalMsg));
        }
        checkResult.setCode(this.code);
        checkResult.setIfPass(false);
        return checkResult;
    }

    @Override
    public void compile(Map<String, Object> config) {
        String expressionConfig = MapUtils.getString(config, "rule");
        if (StringUtils.isNotEmpty(expressionConfig)) {
            this.expression = AviatorEvaluator.compile(expressionConfig);
        }
        this.code = MapUtils.getString(config, "code");
    }


    @Override
    public InsideType getInsideType() {
        return InsideType.NO_INSISE;
    }
}
